/**
 * Created by wry on 2015/4/2.
 */
'use strict';

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};



angular.module('backofficeApp.scoreShopManager.controllers', [])
    //.controller('scoreShopCtrl', ['$scope', '$http', function ($scope, $http) {
    //    $scope.currentPage = 1;
    //    $scope.totalPage = 0;
    //    $scope.pages = [];
    //    $scope.status = ($("#status_select").val() == "") ? "all" : $("#status_select").val();
    //
    //
    //    $scope.getGoodsList = function (pageNo) {
    //        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getScoreShopList/' + $scope.status + "/" + pageNo, {//
    //            headers: {'Content-Type': 'application/json;charset=utf-8'}
    //        }).success(function (data) {
    //            $scope.goodsList = [];
    //            var result = data.data[0];
    //            result.forEach(function (re) {
    //                if (re.images != null)
    //                    re.imageURL = fastDfsHostIp + re.images;
    //                re.createTime = re.create_time;
    //                $scope.goodsList.push(re);
    //            });
    //            $scope.totalPage = Math.ceil(Number(data.data[1][0].pages) / 10);
    //        }).error(function () {
    //        });
    //    };
    //
    //    $scope.getGoodsList(1);
    //
    //
    //    $scope.selectStatus = function() {
    //        $scope.status = ($("#status_select").val() == "") ? "all" : $("#status_select").val();
    //        $scope.searchGoods();
    //    }
    //
    //
    //    $scope.addGoods = function () {
    //
    //        $('#goods_modal').modal('show');
    //        $scope.popupTitle = "添加商品";
    //        $("#loginId").prop('disabled', false);
    //        $('#saveButton').show();
    //        $('#updateButton').hide();
    //        $('#goodsName').val("");
    //        $('#goodsDesc').val("");
    //        $('#inventory').val("");
    //        $('#price').val("");
    //        $('#pict').val("");
    //        $('#pict').attr("required",true);
    //        $scope.image = null;
    //        $scope.goods = {};
    //        $scope.goods.name = "";
    //        $scope.goods.desc = "";
    //        $scope.goods.inventory = "";
    //        $scope.goods.price = "";
    //    };
    //
    //    $scope.updateGoods = function (goods) {
    //        $('#goods_modal').modal('show');
    //        $scope.popupTitle = "修改商品";
    //        $("#loginId").prop('disabled', false);
    //        $('#saveButton').hide();
    //        $('#updateButton').show();
    //        $scope.updateId = goods.id;
    //        $('#goodsName').val(goods.product_name);
    //        $('#goodsDesc').val(goods.product_desc);
    //        $('#inventory').val(goods.inventory_level);
    //        $('#price').val(goods.price);
    //        $('#editor_img').attr("src",goods.imageURL);
    //        $('#pict').val("");
    //        $('#pict').attr("required",false);
    //        $scope.image = null;
    //        $scope.goods = {};
    //        $scope.goods.name = goods.product_name;
    //        $scope.goods.desc = goods.product_desc;
    //        $scope.goods.inventory = goods.inventory_level;
    //        $scope.goods.price = goods.price;
    //    };
    //
    //    $scope.selectFile = function (files) {
    //        $scope.image = files[0];
    //    };
    //
    //    $scope.saveAdd = function (goods, update) {
    //        if (goods.name == "") {
    //            return;
    //        }
    //        if (goods.desc == "") {
    //            return;
    //        }
    //        if (goods.inventory == "") {
    //            return;
    //        }
    //        if (goods.price == "") {
    //            //$('#goodsDesc').css("border","1px solid red");
    //            return;
    //        }
    //        if($scope.image == null && update != "update"){
    //            return;
    //        }
    //
    //        var fd = new FormData();
    //        fd.append('image1', $scope.image);
    //        fd.append('productName', goods.name);
    //        fd.append('productDesc', goods.desc);
    //        fd.append('inventoryLevel', goods.inventory);
    //        fd.append('price', goods.price);
    //        if (update == "update") {
    //            fd.append('cId', $scope.updateId);
    //        }
    //
    //        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addOneGoods', fd, {
    //            transformRequest: angular.identity,
    //            headers: {'Content-Type': undefined}
    //        }).success(function (data) {
    //            $('#goods_modal').modal('hide');
    //            $scope.getGoodsList($scope.currentPage);
    //        }).error(function (data) {
    //        });
    //    };
    //
    //    $scope.changeStatus = function (id, status) {
    //
    //        var input = {
    //            id: id,
    //            status: status
    //        };
    //
    //        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/changeStatus', input, {
    //            headers: {'Content-Type': 'application/json;charset=utf-8'}
    //        }).success(function (data) {
    //            $scope.getGoodsList($scope.currentPage);
    //        }).error(function (data) {
    //        });
    //    };
    //
    //    $scope.onSelectPage = function (page) {
    //        $scope.currentPage = page;
    //        $scope.getGoodsList(page);
    //    };
    //
    //    $scope.searchGoods = function(){
    //        var name = $("#goods_search").val();
    //        if(name == ""){
    //            $scope.getGoodsList(1);
    //            return;
    //        }
    //        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchGoods/' + $scope.status + "/" + name, {//
    //            headers: {'Content-Type': 'application/json;charset=utf-8'}
    //        }).success(function (data) {
    //            $scope.goodsList = [];
    //            var result = data.data;
    //            result.forEach(function (re) {
    //                if (re.images != null)
    //                    re.imageURL = fastDfsHostIp + re.images;
    //                re.createTime = re.create_time;
    //                $scope.goodsList.push(re);
    //            });
    //            $scope.totalPage = 1;
    //        }).error(function () {
    //        });
    //    }
    //
    //}])
    .controller('exchangeRecordCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.currentPage = 1;
        $scope.totalPage = 1;
        $scope.pages = [];

        $scope.actionList = [
            {
                name: 'bug被采纳',
                action: 8,
                value: 10
            },
            {
                name: '建议被采纳',
                action: 9,
                value: 20
            }
        ];

        $scope.addScore = function (action, userId) {

            if (!action || !userId) {
                return;
            }

            var input = {
                userId: userId,
                userActionType: action
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addScore', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.userId = '';
                $scope.action = null;
                if (data.result.status == 0) {
                    alert(data.result.message)
                } else {
                    alert('添加成功！')
                }

            }).error(function (data) {
            });
        };

        $scope.actionList = [
            {
                name: 'bug被采纳',
                action: 8,
                value: 10
            },
            {
                name: '建议被采纳',
                action: 9,
                value: 20
            }
        ];

        $scope.statusSelect = [
            {
                name: '申请中',
                status: 0
            },
            {
                name: '兑换中',
                status: 2
            },
            {
                name: '兑换成功',
                status: 1
            },
            {
                name: '兑换失败',
                status: -1
            }
        ];

        //$scope.getExchangeRecord = function (status) {
        //    var opt = {
        //        pageNum: $scope.currentPage
        //    };
        //    if (status != null) {
        //        opt.status = status
        //    }
        //    $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getExchangeRecordList', opt, {
        //        headers: {'Content-Type': 'application/json;charset=utf-8'}
        //    }).success(function (data) {
        //        $scope.totalPage = data.data.pages;
        //        $scope.exchangeList = [];
        //        var result = data.data.recordList;
        //        result.forEach(function (temp) {
        //            temp.updateTime = (temp.status == 0 ? temp.createTime : temp.createTime) * 1000;
        //            $scope.exchangeList.push(temp);
        //        })
        //
        //    }).error(function (data) {
        //
        //    });
        //};

        //$scope.getExchangeRecord(null);


        $scope.searchGoods = function(){

            var productname  = null;
            var status = null;
            if($scope.productName!=null && $scope.productName!=''){
                productname = $scope.productName;
            }
            if($scope.status !=null){
                status = $scope.status;
            };
            var opt = {
                name: productname,
                status: status,
                pageNum: $scope.currentPage,
                username : $scope.userName
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchExchangeGoods',opt, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                console.debug(data);
                $scope.totalPage = data.data.pages;
                $scope.exchangeList = [];
                var result = data.data.recordList;
                result.forEach(function (temp) {
                    var item = {};
                    item.id = temp.id;
                    item.productName = temp.product_name;
                    item.exchangeNum = temp.exchange_num;
                    item.productPrice = temp.product_price;
                    item.nickName = temp.nickName;
                    item.userName = temp.user_name;
                    item.mobile = temp.mobile;
                    item.address = temp.address;
                    item.status = temp.status;
                    item.createTime = temp.create_time;
                    item.communityName = temp.communityName;
                    item.remark = temp.remark;
                    item.updateTime = (temp.status == 0 ? item.createTime : item.createTime) * 1000;
                    $scope.exchangeList.push(item);
                })
                //$scope.currentPage = pages;
            }).error(function () {
            });
        }

        //$scope.searchGoods();

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            //$scope.getExchangeRecord($scope.status);
            $scope.searchGoods();
        };

        $scope.getExchangeRecordList = function (page) {
            $scope.currentPage = 1;
            $scope.searchGoods();
        }

        $scope.examineProduct = function (remark) {

            var input = {
                orderId: $scope.orderId,
                orderStatus: $scope.orderStatus,
                remark: remark
            };
            console.debug(input);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/examineProduct', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //$scope.getExchangeRecord($scope.status);
                $('#remark_model').modal('hide');
                $scope.searchGoods();
            }).error(function (data) {

            });

        }

        $scope.orderId = null;
        $scope.orderStatus = null;

        $scope.showModal = function (id,status){

            $scope.remark = "";
            $scope.orderId = id;
            $scope.orderStatus = status;
            $('#remark_model').modal('show');
        }

    }]).
    controller('addScoreCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.data = {scoreAddRason: '情值商城上线前您赚的情值'};

        $scope.addScoreManual = function (data) {
            console.debug(data);
            data.scoreAddCount = Number(data.scoreAddCount);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/addScoreManual', data, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {
                    alert('添加成功');
                    $scope.data = {
                        userId: '',
                        scoreAddCount: '',
                        scoreAddRason: '情值商城上线前您赚的情值'
                    };
                } else {
                    alert('添加失败')
                }
            }).error(function (data) {

            });
        }

        var imparry = {};
        $scope.selectFile = function (files) {
            $scope.files = files[0]

            var value;
            var file = files[0];
            console.debug(file.name);

            if(file.name.substring(file.name.indexOf('.')+1) != 'csv' && file.name.substring(file.name.indexOf('.')+1) != 'CSV') {
                alert('文件类型错误，只能导入csv文件！');
                return;
            }
            var reader = new FileReader();
            reader.onload = function () {
                value = this.result;
                console.debug(value);
                imparry = value.split("\n");
            };
            reader.readAsText(file);

        };

        $scope.importScoreManual = function(){

            bootbox.confirm('是否确定导入?', function (result) {

                if ($scope.files == null) {
                    alert('请选择文件');
                    return;
                }
                if (result) {
                    //var fd = new FormData();
                    //if ($scope.files != null) {
                    //    fd.append('file1', $scope.files);
                    //    console.debug($scope.files);
                    //}

                        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/importScoreManual', imparry, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.files = null;
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        }


    }]).
    controller('addScoreLogCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {//TODO: 2015-4-14

        $scope.pages = 0;
        $scope.page = 1;

        $scope.selectPage = function (page) {
            if ($scope.search != null) {
                searchFrontendUser($scope.search.selectedCommunity.objId, $scope.search.mobilePhone, $scope.search.nickName, $scope.search.isVUser, $scope.search.isTalent, page)
            }
        };

        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getAllCommunity', {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (result) {
            //$scope.search.selectedCommunity = "";
            $scope.communityList = result.data;
        }).error(function () {
        });

        /**
         * 弹出框，修改用户信息
         * @param user
         */
        $scope.saveUserInfo = function (user) {
            var tempUser = {
                nickName: user.nickName,
                roomUnit: user.roomUnit,
                roomNumber: user.roomNumber
            };
            $http.put('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/updateUser/' + user.objId, tempUser, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#userDetail').modal('hide');
            }).error(function () {
            });
        }

        function searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent, currentPage) {

            $scope.showErrorForQueryCondition = false;
            $('#errorMsg').html('');

            if (communityObjId == null) {
                $scope.showErrorForQueryCondition = true;
                $('#errorMsg').html('请选择小区!');
                return;
            }
            if (mobilePhone == null || mobilePhone == '') {
                mobilePhone = 'all';
            }
            if (nickName == null || nickName == '') {
                nickName = 'all';
            }
            if (isVUser == null || isVUser == '') {
                isVUser = 'all';
            }
            if (isTalent == null || isTalent == '') {
                isTalent = 'all';
            }

            var startDate = '';
            if ($("#startDate").val() == null || $("#startDate").val() == '') {
                startDate = '2000-01-01'
            } else {
                startDate = $("#startDate").val();
            }

            var endDate = '';
            if ($("#endDate").val() == null || $("#endDate").val() == '') {
                endDate = '2100-01-01'
            } else {
                endDate = $("#endDate").val();
            }

            if (startDate > endDate) {
                $scope.showErrorForQueryCondition = true;
                $('#errorMsg').html('起始日期不能大于终止日期!');
                return;
            }

            var pageSize = 20;
            var startRowNo = (currentPage - 1) * pageSize;

            //找出该小区的所有用户
            /* TODO: URL切换--//new：切换到“积分搜索”， //old：从原来的“用户搜索”*/
            //$http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/searchFrontendUser/' + communityObjId + '/' + mobilePhone + '/' + nickName + '/' + isVUser + '/' + isTalent + '/' + startDate + '/' + endDate + '/' + startRowNo + '/' + pageSize, {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/Score/user/searchFrontendUser/' + communityObjId + '/' + mobilePhone + '/' + nickName + '/' + isVUser + '/' + isTalent + '/' + startDate + '/' + endDate + '/' + startRowNo + '/' + pageSize, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.userList = result.data;
                $scope.pages = 10;
                $scope.userList.items.forEach(function (elem) {
                    if (elem.mobilePhone != null && elem.mobilePhone != '') {
                        elem.source = '手机';
                    } else {
                        if (elem.wechatId != null && elem.wechatId != '') {
                            if (elem.wechatId.substring(0, 2) == 'oW') {
                                elem.source = '微信';
                            } else {
                                elem.source = 'QQ';
                            }
                        } else {
                            elem.source = '未知';
                        }
                    }
                });
            }).error(function () {
            });
        }


        /**
         * 查询小区的所有用户
         * @param communityObjId
         * @param mobilePhone
         * @param nickName
         */
        $scope.searchUser = function (communityObjId, mobilePhone, nickName, isVUser, isTalent) {
            searchFrontendUser(communityObjId, mobilePhone, nickName, isVUser, isTalent, 1);

            /*TODO:*/
            getUserScoreAddRecord();
        };


        /**
         * TODO:获取积分增加记录 2015-4-14
         */
        function getUserScoreAddRecord() {
            //$http.get('http://' + backOfficeHost + '/rest/v1.0/Score/getUserScoreAddRecord/1/54db1a1816d9f5f3652a4cbb/54db1a1816d9f5f3652a4cbb/', {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/Score/getUserScoreAddRecord/1/48/48/', {
                /*TODO：用到是我本地数据库的数据源测试的， */
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $scope.getUserScoreAddRecord_result = result.data;
                $scope.getUserScoreAddRecord_result11 = 10;
                /*$scope.userList.items.forEach(function (elem) {
                 if (elem.mobilePhone != null && elem.mobilePhone != '') {
                 elem.source = '手机';
                 } else {
                 if (elem.wechatId != null && elem.wechatId != '') {
                 if (elem.wechatId.substring(0, 2) == 'oW') {
                 elem.source = '微信';
                 } else {
                 elem.source = 'QQ';
                 }
                 } else {
                 elem.source = '未知';
                 }
                 }
                 });*/
            }).error(function () {
            });
        }


        /**
         * 下拉框选择小区
         */
        $scope.selectCommunity = function () {
            $scope.showErrorForQueryCondition = false;
        }

        /**
         * 获取用户详细信息
         * @param user
         */
        $scope.goDetail = function (user) {
            $('#userDetail').modal('show');
            $scope.userDetail = user;
        }

        /**
         * 弹出黑白操作框
         * @param user
         */
        $scope.blackListConfig = function (user, type) {
            $('#user_modal').modal('show');
            $scope.toBeBlackListUserObjId = user.objId;
            $scope.toBeBlackListUserNickName = user.nickName;
            $("#nickName").prop('disabled', false);

            //拉黑用户，需要显示原因
            if (type == 0) {
                $scope.popupTitle = "把该用户拉黑...";
                $('#reasonInput').show();
                $scope.toBeBlackListUserFrozen = true;
                $scope.toBeBlackListUserReason = null;
                $('#saveButton').text('设置黑名单');
            }
            else {
                $scope.popupTitle = "把该用户拉白...";
                $('#reasonInput').hide();
                $scope.toBeBlackListUserFrozen = false;
                $scope.toBeBlackListUserReason = ' ';
                $('#saveButton').text('设置白名单');
            }
        };

        /**
         * 把用户设置为VUser，或者取消VUser
         */
        $scope.setOrCancelVUser = function (user, messageTitle, authenticationStatus) {
            var tempValue = {
                authenticationStatus: authenticationStatus
            }
            bootbox.confirm(messageTitle, function (result) {
                if (result == true) {
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelVUser/' + user.objId + '/' + user.community.objId, tempValue, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (result) {
                        $scope.userList.items.forEach(function (elem) {
                            if (elem.objId == user.objId) {
                                elem.authenticationStatus = tempValue.authenticationStatus;
                            }
                        });
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        }

        /**
         * 升级为达人，或者取消达人
         * @param user
         * @param messageTitle
         * @param type
         */
        $scope.setOrCancelTalent = function (user, messageTitle, type) {
            if (type == '1') {
                bootbox.prompt(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/' + result + '/' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            } else {
                bootbox.confirm(messageTitle, function (result) {
                    if (result != null && result != '') {
                        $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/setCancelFrontendUserToTalent/' + user.objId + '/ /' + +type, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (result) {
                            $scope.userList.items.forEach(function (elem) {
                                if (elem.objId == user.objId) {
                                    if (type == '1') {
                                        elem.userType = 'Talent';
                                    } else {
                                        elem.userType = 'normalAppUser';
                                    }
                                }
                            });
                        }).error(function () {
                        });
                    }
                }).find("div.modal-dialog").css({width: '30%'});
            }
        }

        /**
         * 保存黑白操作设置
         * @param userObjId
         * @param toBeBlackListUserFrozen
         * @param reason
         */
        $scope.saveBlackListOrWhiteList = function (userObjId, toBeBlackListUserFrozen, reason) {
            if (toBeBlackListUserFrozen == true) {
                var tempFrozenReason = {
                    frozenOrNot: true,
                    reason: reason
                }
                if (reason == null || reason == '') {
                    return;
                }
            } else {
                var tempFrozenReason = {
                    frozenOrNot: false,
                    reason: reason
                }
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/putFrontendUserToBlackList/' + userObjId, tempFrozenReason, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (result) {
                $('#user_modal').modal('hide');
                $scope.userList.items.forEach(function (elem) {
                    if (elem.objId == userObjId) {
                        elem.frozenOrNot = tempFrozenReason.frozenOrNot;
                        elem.reason = tempFrozenReason.reason;
                    }
                });
            }).error(function () {
            });
        }
    }]).
    controller('scoreShopSearchValueCtrl', ['$scope', '$http','CommunityService', function ($scope, $http, communityService) {

        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];
        $scope.communityList = communityService.getAllCommunityService();

        $scope.getAtList = function (input) {
            if (!input||input.communityName == null) {
                return;
            }
            if (!input||input.userName == null) {
                return;
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/searchValue', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data;
                $scope.totalPage = 1;
            }).error(function (data) {
            });
        };
        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getGoodsList(page);
        };
        $scope.getGoodsList = function(page){
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getCommunityScoreList/' + $scope.input.communityName +'/'+page, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.data;
                $scope.totalPage = Math.ceil(Number(data.data.pages)/10);
            }).error(function () {
            });
        };
        $scope.showScoreDetails = function (result) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getUserScoreList/' + result.objId, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.scoreList = data.data;
            }).error(function () {
            });
            $('#scoreDiv').modal('show');
            $('#communityName').html(result.community.communityName);
            $('#userID').html(result.objId);
            $('#userName').html(result.nickName);
            //$('#type').html();
        };
    }]).
    controller('scoreShopSummaryStatsCtrl', ['$scope', '$http','CommunityService', function ($scope, $http, communityService) {

        $scope.allCommunities = [];
        //$scope.communities = [];
        $scope.totalScoreGained = 0;
        $scope.totalScoreConsumed = 0;
        $scope.totalCurrentScore = 0;
        $scope.startDate = '';
        $scope.endDate = '';

        $scope.communityList = communityService.getAllCommunityService();

        $scope.getCommunityStatsData = function(communityId, startDate, endDate){
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/score/getAllCommunityStats/' + communityId + "/" + startDate + "/" + endDate, {//
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.totalScoreGained += data.data.scoreGained;
                $scope.totalScoreConsumed += data.data.scoreConsumed;
                $scope.totalCurrentScore += data.data.currentScore;
                $scope.allCommunities.push(data.data);
            }).error(function () {
            });
        }
        $scope.input= {communityName:'all'};
        $scope.getCommunityStats = function (input) {
            $scope.reset();
            $scope.allCommunities = [];

            var comm = input.communityName == undefined || input.communityName == null || input.communityName == '' ? 'all' : input.communityName;
            var startDate = input.startDate == undefined || input.startDate == null || input.startDate == '' ? 'all' : input.startDate;
            var endDate = input.endDate == undefined || input.endDate == null || input.endDate == '' ? 'all' : input.endDate;

            console.info($scope.communityList.data)

            if(startDate == 'all')
                $scope.startDate = '开始'
            else
                $scope.startDate = input.startDate
            if(endDate == 'all')
                $scope.endDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
            else
                $scope.endDate = input.endDate

            if(comm == 'all'){
                $scope.communityList.data.forEach(function(community){
                    $scope.getCommunityStatsData(community.objId, startDate, endDate)
                });
            }else{
                $scope.getCommunityStatsData(comm, startDate, endDate)
            }
        };

        $scope.reset = function(){
            $scope.totalScoreGained = 0;
            $scope.totalScoreConsumed = 0;
            $scope.totalCurrentScore = 0;
        };

        $scope.validateDate = function(input){
            if(input == null){
                return;
            }
            if (input.startDate != null && input.startDate != '') {
                $scope.startDate = input.startDate;
            }else{
                $scope.startDate = '';
            }
            if(input.endDate != null&& input.startDate != ''){
                $scope.endDate = input.endDate;
            }else{
                $scope.endDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
            }
        };

    }]).
    directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    });